#include "queryPlayRecordResMessage.h"
#include "jsonUtils.h"
#include "operatorResponse.h"
#include "jsonUtils.h"

QueryPlayRecordResMessage::QueryPlayRecordResMessage(MtpProtocol* packet) : MtpMessage(packet)
{
}

QueryPlayRecordResMessage::QueryPlayRecordResMessage(MtpMessage* src) : MtpMessage(new MtpProtocol(L"queryPlayRecordRes", (MtpProtocol*)src->getPacket()))
{
}

QueryPlayRecordResMessage::~QueryPlayRecordResMessage()
{
	if (!playRecords.empty()) {
		for (std::list<PlayRecord*>::iterator it = playRecords.begin(); it != playRecords.end();++it) {
			PlayRecord*& p = *it;
			if (p) {
				delete p;
				p = NULL;
			}
		}
		playRecords.clear();
	}
}

void QueryPlayRecordResMessage::fromJson(const std::wstring& json)
{
	if (!json.empty()) {
		OperatorResponse res;
		JsonDoc& doc = res.jsonDeserialize(json);
		if (res.isSuccess()) {
			const JsonValue::ConstMemberIterator& it = doc.FindMember(L"data");
			if (it != doc.MemberEnd() && it->value.IsArray()) {
				rapidjson::GenericArray<true, JsonValue> arr = it->value.GetArray();
				for (JsonValue::ConstValueIterator v = arr.Begin();v != arr.End();++v) {
					if (v->IsObject()) {
						PlayRecord* item = new PlayRecord();
						item->fromJson(*v);
						playRecords.push_back(item);
					}
				}
			}
		}
	}
}

void QueryPlayRecordResMessage::decodeBody()
{
	MtpMessage::decodeBody();
	fromJson(jsonContent);
}

void QueryPlayRecordResMessage::encodeBody()
{
	OperatorResponse res(true);
	JsonDoc& doc = res.jsonSerialize();
	if (!playRecords.empty()) {
		JsonValue arr(rapidjson::kArrayType);
		for (std::list<PlayRecord*>::const_iterator it = playRecords.begin(); it != playRecords.end(); ++it) {
			PlayRecord* const& p = *it;
			JsonValue item(rapidjson::kObjectType);
			p->toJson(item, doc.GetAllocator());
			arr.PushBack(item, doc.GetAllocator());
		}
		doc.AddMember(L"data", arr, doc.GetAllocator());
	}
	jsonContent = JsonUtils::jsonStr(doc);
	MtpMessage::encodeBody();
}
